# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import os

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
快手小剧场-下载视频
根据关键词下载视频
"""
class Test_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            "User-Agent": "DORORO-android",
            "Content-Type": "application/x-www-form-urlencoded"
        }

    def get_serach(self):
        postData = {
            "mod": "HUAWEI%28CHE-TL00H%29",
            "lon": "0",
            "country_code": "CN",
            "userId": "",
            "kpf": "ANDROID_PHONE",
            "did": "ANDROID_f6111aaf28260cf6",
            "kpn": "DORORO",
            "net": "WIFI",
            "app": "0",
            "oc": "QUANLIANG",
            "gid": "DFP1E738A613BD6154F657E6F8A2A7316EDD42BBC0DE33A8C81A88BDE78D6A86",
            "egid": "DFP1E738A613BD6154F657E6F8A2A7316EDD42BBC0DE33A8C81A88BDE78D6A86",
            "ud": "",
            "hotfix_ver": "",
            "c": "QUANLIANG",
            "sys": "5.0.2",
            "appver": "1.0.0.128",
            "language": "zh-cn",
            "dororo.api_st": "",
            "lat": "0",
            "ver": "",
            "keyword": "美女",
            "id": "",
        }
        url = "http://dororo-api.muyuanapp.com/rest/dro/home/search"
        html = HttpUtils.do_request("POST", url, self.headers, postData)
        json_data = json.loads(html.text)
        for j in json_data["searchResult"]:
            tubeId = j["tubeId"]  # 根据id查询相关视频
            title = j["name"]  # 视频名称
            count = j["totalEpisodeCount"]  # 共有集数
            folder_name = title + "_" + str(count)
            try:
                print(f"=====创建目录 {folder_name}========")
                os.mkdir(os.getcwd() + "\\video\\" + folder_name)
            except :
                pass
            self.get_contents(folder_name, tubeId)


    def get_contents(self, foldname, tubeId):
        postData = {
            "mod": "HUAWEI%28CHE-TL00H%29",
            "lon": "0",
            "country_code": "CN",
            "userId": "",
            "kpf": "ANDROID_PHONE",
            "did": "ANDROID_f6111aaf28260cf6",
            "kpn": "DORORO",
            "net": "WIFI",
            "app": "0",
            "oc": "QUANLIANG",
            # "gid": "DFP1E738A613BD6154F657E6F8A2A7316EDD42BBC0DE33A8C81A88BDE78D6A86",
            # "egid": "DFP1E738A613BD6154F657E6F8A2A7316EDD42BBC0DE33A8C81A88BDE78D6A86",
            "ud": "",
            "hotfix_ver": "",
            "c": "QUANLIANG",
            "sys": "5.0.2",
            "appver": "1.0.0.128",
            "language": "zh-cn",
            "dororo.api_st": "",
            "lat": "0",
            "ver": "",
            "tubeId": tubeId, # "7x5257671093793379739",
            "reverse": "false",
        }
        url = "http://dororo-api.muyuanapp.com/rest/dro/tube/videos/v2"
        html = HttpUtils.do_request("POST", url, self.headers, postData)
        json_data = json.loads(html.text)
        for j in json_data["videos"]:
            title = j['episode']['name']
            url_video = j['mainMvUrls'][0]['url']
            print(f"====Dowload {title}======")
            video_res = requests.get(url_video, headers=self.headers, stream=True)
            with open(os.getcwd() + "\\video\\" + foldname + "\\" + title + ".mp4",'wb') as f:
                f.write(video_res.content)
                f.close
            print("====下载完成======")


if __name__ == '__main__':
    test_get = Test_Get()
    test_get.get_serach()